package com.grad.why.studentsystem.controller;

import com.grad.why.studentsystem.domain.ChooseCourse;
import com.grad.why.studentsystem.domain.Course;
import com.grad.why.studentsystem.domain.Coursestandard;
import com.grad.why.studentsystem.domain.current.CurrentChooseCourseInfo;
import com.grad.why.studentsystem.domain.current.CurrentClassinfo;
import com.grad.why.studentsystem.service.ChooseCourseService;
import com.grad.why.studentsystem.service.CourseStandardService;
import com.grad.why.studentsystem.service.OptionparamsService;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/studentManageSystem")
@Controller
public class ChooseCourseController {
    @Autowired
    private ChooseCourseService chooseCourseService;

    @Autowired
    private OptionparamsService optionparamsService;

    @Autowired
    private CourseStandardService courseStandardService;


    @RequestMapping("/getChooseCourseInfos")
    @ResponseBody
    public Object getClassInfoList(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "order") String order
    ) {
        try {
            List<CurrentChooseCourseInfo> rows = chooseCourseService.getChooseCourseInfos(offset, limit, search);
            long total = chooseCourseService.getChooseCourseInfosLength(search);
            Map<String, Object> result = new HashMap<>(2);
            result.put("rows", rows);
            result.put("total", total);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/deleteChooseCourseByIds/{ids}")
    @ResponseBody
    public String deleteChooseCourseByIds(@PathVariable("ids")String ids){
        try{
            String[] idArray = ids.split("-");
            for(String s : idArray){
                int rows = chooseCourseService.deleteChooseCourseInfoById(Integer.parseInt(s));
                if(rows <= 0){
                    return null;
                }
            }
            return "OK";
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/addChooseCourseInfoBySid/{studentId}")
    @ResponseBody
    public String addChooseCourseInfoBySid(ChooseCourse chooseCourse, @Param("studentId") String studentId){
        try{
            int maxId = chooseCourseService.getMaxChooseCourseId() + 1;
            chooseCourse.setChooseid(maxId);
            int count = chooseCourseService.isExistChooseCourseInfo(chooseCourse);
            if(count == 0){
                int rows = chooseCourseService.insertEntity(chooseCourse);
                if(rows <= 0){
                    return null;
                }else{
                    return "OK";
                }
            }else{
                return "添加失败,选课信息重复!";
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/addChooseCourseInfoBySname/{stuName}")
    @ResponseBody
    public String addChooseCourseInfoBySname(ChooseCourse chooseCourse, @PathVariable("stuName") String stuName){
        try{
            int rows = chooseCourseService.getCountOfStudentName(stuName);
            if(rows == 0){
                return "该学生不存在,请重试!";
            }
            if(rows > 1){
                return "有学生重名，请输入学号进行添加";
            }else{
                int studentId = chooseCourseService.getStudentIdByStudentName(stuName);
                chooseCourse.setSid(studentId);
                int count = chooseCourseService.isExistChooseCourseInfo(chooseCourse);
                if(count == 0){
                    int maxId = chooseCourseService.getMaxChooseCourseId() + 1;
                    chooseCourse.setSid(studentId);
                    chooseCourse.setChooseid(maxId);
                    rows = chooseCourseService.insertEntity(chooseCourse);
                    if(rows <= 0){
                        return null;
                    }else{
                        return "OK";
                    }
                }else{
                    return "添加失败,选课信息重复!";
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/updateChooseCourse")
    @ResponseBody
    public String updateChooseCourse(ChooseCourse chooseCourse){
        try{
            int studentId = chooseCourse.getSid();
            int isExist = chooseCourseService.checkStudentIsExist(studentId);
            if(isExist <= 0){
                return null;
            }else{
                int rows = chooseCourseService.updateChooseCourseInfoByEntity(chooseCourse);
                if(rows<=0){
                    return null;
                }
            }
            return "OK";
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/uploadChooseCourseInfos")
    @ResponseBody
    public String uploadChooseCourseInfos(@RequestParam("file") MultipartFile file){
        try{
            String fileUploadRootPath = optionparamsService.getParamValueByParamName("fileRootPath");
            String fileName = file.getOriginalFilename();
            String uploadCurrentFileName = fileUploadRootPath+"uploadChooseCourseInfo/"+ new Date().getTime() + fileName;

            File fileRootPath = new File(fileUploadRootPath+"uploadChooseCourseInfo");

            if(!fileRootPath.exists()){
                fileRootPath.mkdirs();
            }

            FileOutputStream out = new FileOutputStream(uploadCurrentFileName);
            out.write(file.getBytes());
            out.flush();
            out.close();

            int n = chooseCourseService.addStudentInfosByExcelFile(uploadCurrentFileName);
            if(n<=0){
                return "添加失败";
            }else{
                return "添加"+n+"条数据";
            }
            //上传学生信息逻辑
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/checkScoreLimitedIsRight")
    @ResponseBody
    public String checkScoreLimitedIsRight(String cid,String index,String score){
        try{
            Integer transCid = Integer.parseInt(cid);
            Coursestandard coursestandard = courseStandardService.getCourseStandardInfoById(transCid);
            float standardScore = getStandardScoreByIndex(coursestandard,Integer.parseInt(index));
            Float transScore = Float.parseFloat(score);
            if(transScore > standardScore){
                return "该类评分范围是0<=x<="+standardScore;
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/initQxAndLabel/{cid}")
    @ResponseBody
    public String[] initQxAndLabel(@PathVariable("cid") String cid){
        try{
            String flag = "";
            String score = "";
            String[] result = new String[2];
            Integer transCid = Integer.parseInt(cid);
            Coursestandard coursestandard = courseStandardService.getCourseStandardInfoById(transCid);
            if(coursestandard.getQ1()>0){
                flag += "0 ";
                score += coursestandard.getQ1()+" ";
            }
            if(coursestandard.getQ2()>0){
                flag += "1 ";
                score += coursestandard.getQ2()+" ";
            }
            if(coursestandard.getQ3()>0){
                flag += "2 ";
                score += coursestandard.getQ3()+" ";
            }
            if(coursestandard.getQ4()>0){
                flag += "3 ";
                score += coursestandard.getQ4()+" ";
            }
            if(coursestandard.getQ5()>0){
                flag += "4 ";
                score += coursestandard.getQ5()+" ";
            }
            if(coursestandard.getQ6()>0){
                flag += "5 ";
                score += coursestandard.getQ6()+" ";
            }
            if(coursestandard.getQ7()>0){
                flag += "6 ";
                score += coursestandard.getQ7()+" ";
            }
            result[0] = flag.trim();
            result[1] = score.trim();
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public float getStandardScoreByIndex(Coursestandard coursestandard,int index){
        float[] qx = new float[7];
        qx[0] = coursestandard.getQ1();
        qx[1] = coursestandard.getQ2();
        qx[2] = coursestandard.getQ3();
        qx[3] = coursestandard.getQ4();
        qx[4] = coursestandard.getQ5();
        qx[5] = coursestandard.getQ6();
        qx[6] = coursestandard.getQ7();
        return qx[index];
    }
}
